/**
 * @description 对每一个完整行(字符串)进行处理
 */
const dbg = require("debug")("[GoodLineProcess]");
dbg.enabled = true;
// const mongo = require("./mongo");
const models = require("./mysql")

const store = {
    boundary: "",
    pic_start: false, //用于检查是否已经开始解析图片
    pic: {
        cid: "",
        image_type: "",
        content: ""
    },
    phase: 0
}

/**
 * 
 * @param {String} line 
 * @param {Number} chunk_count
 * @param {String} filename the filename of .mht file
 * @returns {Promise}
 */
function GoodLineProcess(line, chunk_count, filename) {
    return new Promise(async (resolve) => {
        if (line.length == 0) {
            return resolve("length == 0");
        }
        if (store.phase == 0) {
            if (line.startsWith("\tboundary=")) {
                let boundary = line.replace("\tboundary=", "").split("\"")[1];
                dbg("boundary is ", boundary);
                store.boundary = boundary;
                await models.MhtFile.sync({
                    force: true
                });
                await models.HtmlMsg.sync({
                    force: true
                });
                await models.Image.sync({
                    force: true
                });
                models.MhtFile.create({
                    filename: filename,
                    boundary: boundary,
                    visited: false
                }).then((doc) => {
                    "debugger"
                    dbg("boundary saved!!");
                    store.phase = 1;
                    resolve("go to phase 1");
                })
                // let mhtFile = mongo.MhtFile({
                //     filename: filename,
                //     boundary: boundary
                // });
                // mhtFile.save().then(() => {
                //     dbg("boundary saved!!");
                //     store.phase = 1;
                //     resolve("go to phase 1");
                // })

            } else {
                resolve("null");
            }
        } else if (store.phase == 1) {
            if (line.includes(store.boundary)) {
                store.phase = 2;
                resolve("go to phase 2");
            } else {
                resolve("null");
            }
        } else if (store.phase == 2) {
            if (line.startsWith("Content-Type")) {
                if (line.includes("image/")) {
                    //image
                    if (store.pic_start) {
                        models.Image.create({
                            cid: store.pic.cid,
                            content: store.pic.content,
                            image_type: store.pic.image_type,
                            visited: false,
                            boundary: store.boundary
                        }).then((doc) => {
                            dbg("image type", store.pic.image_type);
                            dbg("image cid", store.pic.cid);
                            dbg(store.pic.content);
                            dbg("-------")
                            // 模拟保存 end
                           "debugger"
                            //重置暂存变量
                            store.pic.image_type = line.replace("Content-Type:", "");
                            store.pic.cid = "";
                            store.pic.content = "";
                            store.phase = 22;
                            store.pic_start = true;

                            resolve("go to 22");
                        })
                        // // let image = new mongo.Image({
                        // //     cid: store.pic.cid,
                        // //     content: store.pic.content,
                        // //     image_type: store.pic.image_type,
                        // //     visited: false,
                        // //     boundary: store.boundary
                        // // });
                        // image.save().then(() => {

                        // })
                    } else {
                        store.pic.image_type = line.replace("Content-Type:", "");
                        store.phase = 22;
                        store.pic_start = true;
                        resolve("go to 22");
                    }
                } else {
                    //html
                    store.phase = 21;
                    resolve("go to 21")
                }
            } else {
                resolve("null");
            }
        } else if (store.phase == 21) {
            //处理html
            if (line.startsWith("<") && line.endsWith(">")) {
                let matched = line.match(/<tr><td.*<\/td><\/tr>/g);
                HtmlMatchedProcess(matched, store.boundary)
                    .then(() => {
                        if (line.includes("</html>")) {
                            store.phase = 1;
                        }
                        resolve("html line processed")
                    })
            } else {
                resolve("not html line");
            }
        } else if (store.phase == 22) {
            if (line.startsWith("Content")) {
                if (line.startsWith("Content-Location")) {
                    let cid = line.replace("Content-Location:{", "").replace("}.dat", "");
                    store.pic.cid = cid;
                    resolve("cid get!");
                } else {
                    resolve("Content-Transfer-Encoding");
                }
            } else {
                if (line.includes(store.boundary)) {
                    store.phase = 2;
                    resolve("go to phase 2");
                } else {
                    store.pic.content += `${line}\n`;
                    resolve("picture content add!");
                }
            }
        }

    })
}

/**
 * 
 * @param {String[]|null} matched 
 * @param {String} boundary
 */
function HtmlMatchedProcess(matched, boundary) {
    return new Promise((resolve) => {
        if (Array.isArray(matched)) {
            /**
             * @done 按顺序存储matched的每一项到数据库里
             */
            let matched_copy = matched.map(e => e);
            let Generator = function* Generator() {
                for (let i = 0; i < matched_copy.length; i++) {
                    let img_matched = matched_copy[i].match(/<IMG src="{([a-zA-Z0-9\-])*}.dat">/ig);
                    if (Array.isArray(img_matched)) {
                        for (let img_tag of img_matched) {
                            let matched_cid = img_tag.match(/{([a-zA-Z0-9\-]*)}.dat/)
                            // let cid_dat = matched_cid[0];//like "{7551CE52-8840-447f-BF14-D38235C969BE}.dat"
                            let cid = matched_cid[1]; //like "7551CE52-8840-447f-BF14-D38235C969BE"
                            matched_copy[i] = matched_copy[i].replace(
                                img_tag,
                                `<IMG src="cid:${cid}">`
                            )
                        }
                        // dbg("before:",matched[i]);
                        // dbg("after:",matched_copy[i])
                    }
                    yield new Promise((r) => {
                        models.HtmlMsg.create({
                            html:matched_copy[i],
                            visited:false,
                            boundary:boundary
                        }).then((doc)=>{
                            r(doc);
                        })
                        // let html_msg = new mongo.HtmlMsg({
                        //     html: matched_copy[i],
                        //     visited: false,
                        //     boundary: boundary
                        // });
                        // html_msg.save().then(arg => r(arg));
                    })
                }
                return "ok";
            }
            let g = Generator();
            let it = g.next();
            let BootFn = function Boot() {
                if (!it.done) {
                    it.value.then((saved_doc) => {
                        dbg(saved_doc['html'])
                        it = g.next();
                        BootFn();
                    })
                } else {
                    resolve("all matched processed");
                }
            };
            BootFn();

        } else {
            //没有任何匹配
            resolve("none matched");
        }
    })
}
module.exports = {
    GoodLineProcess
};